﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using ResxWebEditor.Code;

namespace MLM.AdminCP.Pages
{
    public partial class LanguageImportExport : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ExportBtn.Click += new EventHandler(ExportBtn_Click);
            ImportBtn.Click += new EventHandler(ImportBtn_Click);
            lstResX.SelectedIndexChanged += new EventHandler(lstResX_SelectedIndexChanged);
            if (!IsPostBack)
            {
                GetResX();
                FillLanguages();
            }
            ddLanguage.SelectedIndexChanged += new EventHandler(ddLanguage_SelectedIndexChanged);
        }

        void ddLanguage_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                var filePath = "~/" + lstResX.SelectedItem.Text.Replace("\"", "/");
                var fileNameOnly = Path.GetFileNameWithoutExtension(filePath);
                var ext = Path.GetExtension(filePath);
                var folder = Path.GetDirectoryName(filePath);
                var selectedLanguageCode = ddLanguage.SelectedValue;
                if (selectedLanguageCode != "")
                {
                    ValidateSelectFile.ValidationExpression = @"^" + fileNameOnly + ext + "." + selectedLanguageCode +
                                                              ".resx$";
                }
                else
                {
                    ValidateSelectFile.ValidationExpression = @"^" + fileNameOnly + ext + ".resx$";
                }
            }catch(Exception)
            {
                MessageLbl.Text = "You must select a file!";
            }
        }

        void lstResX_SelectedIndexChanged(object sender, EventArgs e)
        {
            var filePath = "~/" + lstResX.SelectedItem.Text.Replace("\"", "/");
            var fileNameOnly = Path.GetFileNameWithoutExtension(filePath);
            var ext = Path.GetExtension(filePath);
            var folder = Path.GetDirectoryName(filePath);
            var selectedLanguageCode = ddLanguage.SelectedValue;
            if (selectedLanguageCode!="")
            {
                ValidateSelectFile.ValidationExpression = @"^" + fileNameOnly + ext + "." + selectedLanguageCode + ".resx$";   
            }
            else
            {
                ValidateSelectFile.ValidationExpression = @"^" + fileNameOnly + ext + ".resx$";
            }           
        }

        void ImportBtn_Click(object sender, EventArgs e)
        {
            var fileUrl = "~/" + lstResX.SelectedItem.Text.Replace("\"", "/");
            try
            {
                var filePath = "~/" + lstResX.SelectedItem.Text.Replace("\"", "/");
                var fileNameOnly = Path.GetFileNameWithoutExtension(filePath);
                var ext = Path.GetExtension(filePath);
                var folder = Path.GetDirectoryName(filePath);
                var selectedLanguageCode = ddLanguage.SelectedValue;
                var completePath = "";
                if (selectedLanguageCode != "")
                {
                    completePath = folder + "\\App_LocalResources\\" + fileNameOnly + ext + "." + selectedLanguageCode +
                                    ".resx";
                }
                else
                {
                    completePath = folder + "\\App_LocalResources\\" + fileNameOnly + ext + ".resx";
                }
                completePath = completePath.Replace("\"", "/").Replace("\\\\","\\");
                string realPath = Server.MapPath(completePath);
                if (File.Exists(realPath))
                {
                    File.Delete(realPath);
                }
                else
                {
                    HttpPostedFile myFile = ImportFile.PostedFile;
                    string sFileName = myFile.FileName;
                    myFile.SaveAs(realPath);
                }
            }
            catch (Exception ex)
            {
                MessageLbl.Text = ex.Message;
            }
        }

        void ExportBtn_Click(object sender, EventArgs e)
        {
            try
            {
                var filePath = "~/" + lstResX.SelectedItem.Text.Replace("\"", "/");
                var fileNameOnly = Path.GetFileNameWithoutExtension(filePath);
                var ext = Path.GetExtension(filePath);
                var folder = Path.GetDirectoryName(filePath);
                var selectedLanguageCode = ddLanguage.SelectedValue;
                var completePath = "";
                if (selectedLanguageCode != "")
                {
                    completePath = folder + "\"App_LocalResources\"" + fileNameOnly + ext + "." + selectedLanguageCode +
                                    ".resx";
                }
                else
                {
                    completePath = folder + "\"App_LocalResources\"" + fileNameOnly + ext + ".resx";
                }
                completePath = completePath.Replace("\"", "/");
                string realPath = Server.MapPath(completePath);
                if (File.Exists(realPath))
                {
                    FileInfo file = new FileInfo(realPath);
                    Response.Clear();
                    Response.ClearHeaders();
                    Response.ClearContent();
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
                    Response.AddHeader("Content-Length", file.Length.ToString());
                    Response.ContentType = "text/plain";
                    Response.Flush();
                    Response.TransmitFile(file.FullName);
                    Response.End();
                }
                else
                {
                    MessageLbl.Text = "Language file not found!";
                }
            }
            catch (Exception)
            {
                MessageLbl.Text = "Language file not found!";
            }
        }
        /// <summary>
        /// Get all the Resx in the web site and list them in a list
        /// </summary>
        protected void GetResX()
        {
            SortedList<string, string> list = ResXUnified.GetResXInDirectory(ResxPath,
                new GenericPredicate<string, string>(delegate(string[] path)
                {
                    return path[0].Replace(path[1], "").Replace("App_LocalResources", "").Replace("App_GlobalResources", "");
                }));

            foreach (KeyValuePair<string, string> val in list)
                lstResX.Items.Add(new ListItem(val.Key, val.Value));
        }
        private void FillLanguages()
        {
            SortedList<string, string> langs;
            if (Unified != null)
                langs = Unified.GetLanguages();
            else
                langs = new SortedList<string, string>();

            CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);

            SortedList<string, CultureInfo> cults = new SortedList<string, CultureInfo>();
            foreach (CultureInfo culture in cultures)
            {
                if (!cults.ContainsKey(culture.DisplayName))
                {
                    cults.Add(culture.DisplayName, culture);
                }
            }
            ddLanguage.Items.Clear();
            ddLanguage.Items.Add(new ListItem("Default", ""));
            foreach (CultureInfo culture in cults.Values)
            {
                if (!langs.ContainsKey(culture.Name))
                {
                    if (IncludeLanguages == "*" && ExcludeLanguages == "")
                        AddToLanguages(culture);
                    else
                    {
                        List<string> excludes = StringToList(ExcludeLanguages);
                        if (excludes.Contains(culture.Name.ToLowerInvariant()))
                            break;

                        if (IncludeLanguages == "*")
                            AddToLanguages(culture);
                        else
                        {
                            List<string> includes = StringToList(IncludeLanguages);
                            if (includes.Contains(culture.Name.ToLowerInvariant()))
                                AddToLanguages(culture);
                        }
                    }
                }
            }
        }
        protected List<string> StringToList(string str)
        {
            List<string> toReturn = new List<string>();
            string[] splits = str.Split(',', ';');
            foreach (string split in splits)
                toReturn.Add(split.Trim().ToLowerInvariant());

            return toReturn;
        }

        /// <summary>
        /// Add a culture info to the drop down of languages
        /// </summary>
        /// <param name="culture"></param>
        protected virtual void AddToLanguages(CultureInfo culture)
        {
            if (culture.DisplayName.Length > 30)
                ddLanguage.Items.Add(new ListItem(string.Format("{0} ({1})", culture.DisplayName.Substring(0, 30), culture.Name), culture.Name));
            else
                ddLanguage.Items.Add(new ListItem(string.Format("{0} ({1})", culture.DisplayName, culture.Name), culture.Name));
        }
        public string ResxPath
        {
            get
            {
                return (string)(ViewState["ResxPath"] ?? Server.MapPath("~/"));
            }
            set
            {
                ViewState["ResxPath"] = value;
            }
        }
        /// <summary>
        /// The current RESX file selected
        /// </summary>
        protected string CurrentSelection
        {
            get
            {
                return (string)ViewState["FilePath"];
            }
            set
            {
                ViewState["FilePath"] = value;
            }
        }

        protected ResXUnified Unified
        {
            get
            {
                return (ResXUnified)(ViewState["Unified"]);
            }
            set
            {
                ViewState["Unified"] = value;
            }
        }

        public string IncludeLanguages
        {
            get
            {
                return (string)(ViewState["IncludeLanguages"] ?? "*");
            }
            set
            {
                ViewState["IncludeLanguages"] = value;
            }
        }

        public string ExcludeLanguages
        {
            get
            {
                return (string)(ViewState["ExcludeLanguages"] ?? "");
            }
            set
            {
                ViewState["ExcludeLanguages"] = value;
            }
        }
    }
}